package com.leyou.auth.web;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: 授权接口
 * @author 朱正磊
 * @date 2021-04-18 11:30:13
 */
@Slf4j
@RestController
public class AuthController {

    @Resource
    private AuthService authService;

    @Resource
    private JwtProperties jwtProperties;

    /**
     * description: 用户登录
     * @author 朱正磊
     * @date 2021-04-18 11:36:12
     * @param username 用户名
     * @param password 密码
     * @param response 响应对象
     * @param request 请求对象
     */
    @PostMapping("login")
    public ResponseEntity<Void> login(@RequestParam("username") String username,
                                      @RequestParam("password") String password,
                                      HttpServletResponse response, HttpServletRequest request) {
        // 登录
        String token = authService.login(username, password);
        // 设置httpOnly为true表示不允许js操作cookie，设置request表示不允许cookie跨域访问
        // 我们没有设置字符编码是因为token不含有中文，我们同样也没有设置cookie的过期时间是因为cookie
        // 默认浏览器关闭就失效，这符合我们的业务需求
        CookieUtils.newBuilder(response).httpOnly().request(request).build(jwtProperties.getCookieName(), token);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * description: 校验用户登录状态
     * @author 朱正磊
     * @date 2021-04-18 21:39:11
     * @param token JWT
     * @param response 响应对象
     * @param request 请求对象
     * @return 返回用户信息
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN") String token,
                                           HttpServletResponse response, HttpServletRequest request) {
        if (StringUtils.isBlank(token)) {
            // 如果token为空，说明用户未登录，我们就返回401即表示没有访问权限（未授权）
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        try {
            // 解析token
            UserInfo userInfo = JwtUtils.getUserInfo(jwtProperties.getPublicKey(), token);

            // 刷新token，即重新生成token
            String newToken = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());

            // 写入cookie
            CookieUtils.newBuilder(response).httpOnly().request(request).build(jwtProperties.getCookieName(), newToken);

            // 用户已登录，返回用户信息
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            // token已过期或者token已被篡改
            log.error("【授权中心】解析JWT失败！", e);
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }

}
